﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcBoost
{
    /// <summary>
    /// Tool methods for object to dictionary conversion and dictionary manipulation
    /// </summary>
    public static class MvcTools
    {
        public static void Merge<TKey, TValue>(IDictionary<TKey, TValue> d1, IDictionary<TKey, TValue> d2, bool overwrite)
        {
            foreach (var kv in d2)
            {
                if (!d1.ContainsKey(kv.Key)) { d1.Add(kv.Key, kv.Value); }
                else
                {
                    if (overwrite) d1[kv.Key] = kv.Value;
                }

            }
        }

        public static TDynamic Extend<TDynamic>(params object[] attrs) where TDynamic : IDictionary<string, object>, new()
        {
            if (attrs == null) return default(TDynamic);
            var dict = new TDynamic();
            foreach (var obj in attrs)
            {
                var d = ObjectToDictionaryRegistry.Convert(obj);
                if (d != null) Merge(dict, d, true);
            }
            return dict;
        }

        public static Dictionary<string, object> Extend(params object[] attrs)
        {
            return Extend<Dictionary<string, object>>(attrs);
        }

        public static Dictionary<string, object> Dictonary(object obj)
        {
            return Extend(obj);
        }

        public static Dictionary<string, object> Html5fy(IDictionary<string, object> attrs)
        {
            var dict = new Dictionary<string, object>();
            if (attrs != null)
            {
                attrs.ToList().ForEach(kvp => dict.Add(kvp.Key.Replace('_', '-'), kvp.Value));
            }
            return dict;
        }
    }
}
